﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CLEX.Database.DAL;
using CLEX.Host.Implementation.Helpers;
using CLEX.Service.DataContracts;
using CLEX.Service.ServiceContracts;

namespace CLEX.Host.Implementation
{
    public class AdminService : IAdminService
    {
        private readonly IUserDAL userDAL;
        private readonly IPasswordHelper passwordHelper;

        public AdminService(string connectionString)
            : this(
            userDAL: new UserDAL(connectionString),
            passwordHelper: new PasswordHelper())
        {

        }

        public AdminService(IUserDAL userDAL, IPasswordHelper passwordHelper)
        {
            this.userDAL = userDAL;
            this.passwordHelper = passwordHelper;
        }

        public int CreateUser(string username, string password, bool isActive)
        {
            string passwordSalt = passwordHelper.GenerateSalt();
            string hashedPassword = passwordHelper.Hash(password, passwordSalt);
            return userDAL.Insert(username, hashedPassword, passwordSalt, isActive);
        }

        public List<UserData> GetAllUsers()
        {
            return userDAL.Select().Select(p => new UserData(p.UserId, p.Username, p.IsActive)).ToList();
        }

        public void DeleteUser(int userId)
        {
            userDAL.Delete(userId);
        }

        public void UpdateUser(UserData user)
        {
            UserFullData full = userDAL.SelectById(user.UserId);
            userDAL.Update(new UserFullData(user.UserId, user.Username, user.IsActive, full.HashedPassword, full.PasswordSalt));
        }

        public void ChangePassword(int userId, string newPassword)
        {
            UserFullData user = userDAL.SelectById(userId);
            string salt = passwordHelper.GenerateSalt();
            string hash = passwordHelper.Hash(newPassword, salt);
            userDAL.Update(new UserFullData(user.UserId, user.Username, user.IsActive, hash, salt));
        }
    }
}
